package com.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RedisServiceImpl implements RedisService{

    @Autowired
    RedisTemplate redisTemplate = null;

    @Override
    public void execMultiCommand() {
        Object execute = redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.boundValueOps("key_1").set("value_1");
                redisOperations.boundHashOps("hash").put("k_hash_1", "v_hash_1");
                return redisOperations.boundValueOps("key_1").get();
            }
        });
        System.out.println("execMultiCommand:"+execute);
    }

    @Override
    public void execTransaction() {
        Object execute = redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.watch("key_1");
                redisOperations.multi();
                redisOperations.boundValueOps("key_1").set("value_1.1");
                redisOperations.boundHashOps("hash").put("k_hash_1","v_hash_1.1");
                redisOperations.boundValueOps("key_1").get();
                List exec = redisOperations.exec();
                return exec;
            }
        });
        System.out.println("execTransaction:"+execute);
    }

    @Override
    public void execPipeline() {
        Object execute = redisTemplate.executePipelined(new SessionCallback<Object>() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.boundValueOps("key_1").set("value_1.2");
                redisOperations.opsForHash().put("hash", "k_hash_1", "value-hash-1");
                redisOperations.opsForValue().get("key_1");
                return null;
            }
        });
        System.out.println("execPipeline:"+execute);
    }
}
